#include <stdio.h>
#include <string.h>
#include <pthread.h>
#include <stdlib.h>
#include <unistd.h>

// gcc -pthread --std=c99 chap10_2_mutex.c
// 展示 线程同步
pthread_t tid[2];
pthread_t tid1[2];
pthread_t tid2[2];

int count1;
int count2;
pthread_mutex_t my_lock;

#define MAX 100000

// 2个线程同时执行，不做任何同步
void* add0(){
	for(int i=0;i<MAX;i++){
		count1++;
		count2++;
	}
	return (void*)0;
}

// 2个线程同时执行，代码中同步
void* add1(){
	pthread_mutex_lock(&my_lock);
	for(int i=0;i<MAX;i++){
		count1++;
		count2++;
	}
	pthread_mutex_unlock(&my_lock);
	return (void*)0;
}

// 2个线程同时执行，代码中部分同步
void* add2(){
	for(int i=0;i<MAX;i++){
		count1++;
	}
	pthread_mutex_lock(&my_lock);
	for(int i=0;i<MAX;i++){
		count2++;
	}
	pthread_mutex_unlock(&my_lock);
	return (void*)0;
}

int main(void){
	//
	count2 = 0;
	count1 = 0;
	pthread_create(&tid[0], NULL, add0, (void *)NULL);
	pthread_create(&tid[1], NULL, add0, (void *)NULL);
	pthread_join(tid[0], NULL);
	pthread_join(tid[1], NULL);
	printf("count1=%d\n",count1);
	printf("count2=%d\n",count2);

	//
	count2 = 0;
	count1 = 0;
	pthread_create(&tid1[0], NULL, add1, (void *)NULL);
	pthread_create(&tid1[1], NULL, add1, (void *)NULL);
	pthread_join(tid1[0], NULL);
	pthread_join(tid1[1], NULL);
	printf("count1=%d\n",count1);
	printf("count2=%d\n",count2);

	//
	count2 = 0;
	count1 = 0;
	pthread_create(&tid2[0], NULL, add2, (void *)NULL);
	pthread_create(&tid2[1], NULL, add2, (void *)NULL);
	pthread_join(tid2[0], NULL);
	pthread_join(tid2[1], NULL);
	printf("count1=%d\n",count1);
	printf("count2=%d\n",count2);
	// sample out put
	// count1=119366
	// count2=114311

	// count1=200000 // max + 2thread = 200000
	// count2=200000

	// count1=101674
	// count2=200000

}
